<template>
  <div class="mall-diy-designer">
    <div class="designer-header">
      <div class="header-left">
        <el-icon class="back-icon" @click="$router.back()">
          <ArrowLeft />
        </el-icon>
        <span class="title">商城装修</span>
        <el-tag type="success" size="small">{{ currentPage }}</el-tag>
      </div>
      <div class="header-actions">
        <el-button @click="showAIDialog = true" type="primary">
          <el-icon><MagicStick /></el-icon>
          AI设计
        </el-button>
        <el-button @click="handleSave" type="success">
          <el-icon><Select /></el-icon>
          保存
        </el-button>
        <el-button @click="handlePublish">
          <el-icon><Promotion /></el-icon>
          发布
        </el-button>
      </div>
    </div>

    <div class="designer-body">
      <!-- 左侧组件库 -->
      <div class="component-panel">
        <div class="panel-header">组件库</div>
        
        <el-collapse v-model="activeNames" accordion>
          <el-collapse-item title="基础组件" name="basic">
            <div class="component-list">
              <div 
                v-for="comp in basicComponents" 
                :key="comp.type"
                class="component-item"
                draggable="true"
                @dragstart="handleDragStart(comp)"
              >
                <el-icon :size="24" :color="comp.color">
                  <Picture v-if="comp.type === 'banner'" />
                  <Grid v-else-if="comp.type === 'grid'" />
                  <Document v-else />
                </el-icon>
                <div class="comp-info">
                  <div class="comp-name">{{ comp.name }}</div>
                  <div class="comp-desc">{{ comp.desc }}</div>
                </div>
              </div>
            </div>
          </el-collapse-item>

          <el-collapse-item title="商品组件" name="product">
            <div class="component-list">
              <div 
                v-for="comp in productComponents" 
                :key="comp.type"
                class="component-item"
                draggable="true"
                @dragstart="handleDragStart(comp)"
              >
                <el-icon :size="24" :color="comp.color">
                  <ShoppingCart />
                </el-icon>
                <div class="comp-info">
                  <div class="comp-name">{{ comp.name }}</div>
                  <div class="comp-desc">{{ comp.desc }}</div>
                </div>
              </div>
            </div>
          </el-collapse-item>

          <el-collapse-item title="营销组件" name="marketing">
            <div class="component-list">
              <div 
                v-for="comp in marketingComponents" 
                :key="comp.type"
                class="component-item"
                draggable="true"
                @dragstart="handleDragStart(comp)"
              >
                <el-icon :size="24" :color="comp.color">
                  <PriceTag />
                </el-icon>
                <div class="comp-info">
                  <div class="comp-name">{{ comp.name }}</div>
                  <div class="comp-desc">{{ comp.desc }}</div>
                </div>
              </div>
            </div>
          </el-collapse-item>
        </el-collapse>
      </div>

      <!-- 中间移动端预览 -->
      <div class="preview-panel">
        <div class="preview-toolbar">
          <el-button-group>
            <el-button 
              v-for="page in pages" 
              :key="page.key"
              :type="currentPage === page.name ? 'primary' : ''"
              @click="switchPage(page.key)"
              size="small"
            >
              {{ page.name }}
            </el-button>
          </el-button-group>
          
          <el-button-group>
            <el-button @click="handleUndo" :disabled="!canUndo" size="small">
              <el-icon><RefreshLeft /></el-icon>
            </el-button>
            <el-button @click="handleRedo" :disabled="!canRedo" size="small">
              <el-icon><RefreshRight /></el-icon>
            </el-button>
            <el-button @click="handleClear" size="small">
              <el-icon><Delete /></el-icon>
            </el-button>
          </el-button-group>
        </div>

        <div class="mobile-preview">
          <div class="mobile-device">
            <div class="device-header">
              <div class="time">10:24</div>
              <div class="status-bar">
                <el-icon><Connection /></el-icon>
                <el-icon><Iphone /></el-icon>
              </div>
            </div>

            <div 
              class="device-content"
              @drop="handleDrop"
              @dragover.prevent
            >
              <el-empty 
                v-if="components.length === 0" 
                description="拖拽左侧组件到此处"
                :image-size="100"
              >
                <el-button type="primary" size="small" @click="showAIDialog = true">
                  AI生成页面
                </el-button>
              </el-empty>

              <div
                v-for="(comp, index) in components"
                :key="comp.id"
                class="page-component"
                :class="{ active: selectedIndex === index }"
                @click.stop="selectComponent(index)"
              >
                <component :is="renderComponent(comp)" :data="comp.data" />
                
                <div class="component-toolbar">
                  <el-button-group size="small">
                    <el-button @click.stop="moveUp(index)" :disabled="index === 0">
                      <el-icon><Top /></el-icon>
                    </el-button>
                    <el-button @click.stop="moveDown(index)" :disabled="index === components.length - 1">
                      <el-icon><Bottom /></el-icon>
                    </el-button>
                    <el-button @click.stop="copyComponent(index)">
                      <el-icon><DocumentCopy /></el-icon>
                    </el-button>
                    <el-button type="danger" @click.stop="deleteComponent(index)">
                      <el-icon><Delete /></el-icon>
                    </el-button>
                  </el-button-group>
                </div>
              </div>
            </div>

            <div class="device-footer">
              <div class="nav-item active">
                <el-icon><House /></el-icon>
                <span>首页</span>
              </div>
              <div class="nav-item">
                <el-icon><Menu /></el-icon>
                <span>分类</span>
              </div>
              <div class="nav-item">
                <el-icon><ShoppingCart /></el-icon>
                <span>购物车</span>
              </div>
              <div class="nav-item">
                <el-icon><User /></el-icon>
                <span>我的</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧属性配置 -->
      <div class="property-panel">
        <el-tabs v-model="propertyTab">
          <el-tab-pane label="组件属性" name="component">
            <div v-if="selectedComponent" class="property-form">
              <div class="property-title">{{ selectedComponent.name }}</div>
              
              <!-- 轮播图配置 -->
              <template v-if="selectedComponent.type === 'banner'">
                <el-form label-width="70px" size="small">
                  <el-form-item label="高度">
                    <el-input-number v-model="selectedComponent.data.height" :min="100" :max="500" />
                  </el-form-item>
                  <el-form-item label="自动播放">
                    <el-switch v-model="selectedComponent.data.autoplay" />
                  </el-form-item>
                  <el-form-item label="指示器">
                    <el-switch v-model="selectedComponent.data.indicator" />
                  </el-form-item>
                  <el-form-item label="轮播项">
                    <el-button size="small" @click="addBannerItem">添加</el-button>
                    <div v-for="(item, idx) in selectedComponent.data.items" :key="idx" class="banner-item">
                      <el-input v-model="item.image" placeholder="图片URL" size="small" />
                      <el-button size="small" type="danger" link @click="removeBannerItem(idx)">删除</el-button>
                    </div>
                  </el-form-item>
                </el-form>
              </template>

              <!-- 商品列表配置 -->
              <template v-if="selectedComponent.type === 'product-list'">
                <el-form label-width="70px" size="small">
                  <el-form-item label="展示列数">
                    <el-radio-group v-model="selectedComponent.data.columns">
                      <el-radio :label="2">2列</el-radio>
                      <el-radio :label="3">3列</el-radio>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item label="显示标题">
                    <el-switch v-model="selectedComponent.data.showTitle" />
                  </el-form-item>
                  <el-form-item label="显示价格">
                    <el-switch v-model="selectedComponent.data.showPrice" />
                  </el-form-item>
                </el-form>
              </template>

              <!-- 魔方导航配置 -->
              <template v-if="selectedComponent.type === 'grid-nav'">
                <el-form label-width="70px" size="small">
                  <el-form-item label="行数">
                    <el-input-number v-model="selectedComponent.data.rows" :min="1" :max="3" />
                  </el-form-item>
                  <el-form-item label="列数">
                    <el-input-number v-model="selectedComponent.data.cols" :min="3" :max="5" />
                  </el-form-item>
                </el-form>
              </template>
            </div>
            <el-empty v-else description="请选择一个组件" :image-size="80" />
          </el-tab-pane>

          <el-tab-pane label="页面设置" name="page">
            <div class="property-form">
              <el-form label-width="80px" size="small">
                <el-form-item label="页面标题">
                  <el-input v-model="pageData.title" />
                </el-form-item>
                <el-form-item label="页面背景">
                  <el-color-picker v-model="pageData.bgColor" />
                </el-form-item>
                <el-form-item label="分享图片">
                  <el-input v-model="pageData.shareImage" placeholder="分享图片URL" />
                </el-form-item>
              </el-form>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>

    <!-- AI生成对话框 -->
    <el-dialog v-model="showAIDialog" title="AI商城设计助手" width="700px">
      <el-alert 
        title="AI可以帮你快速生成商城页面"
        type="info"
        :closable="false"
        style="margin-bottom: 20px"
      >
        示例：创建一个首页，包含轮播图、分类导航、热门商品、秒杀活动
      </el-alert>
      <el-input
        v-model="aiInput"
        type="textarea"
        :rows="4"
        placeholder="描述你想要的商城页面..."
      />
      <template #footer>
        <el-button @click="showAIDialog = false">取消</el-button>
        <el-button type="primary" @click="handleAIGenerate" :loading="aiGenerating">
          <el-icon><MagicStick /></el-icon>
          生成页面
        </el-button>
      </template>
    </el-dialog>

    <!-- 预览对话框 -->
    <el-dialog v-model="showPreview" title="页面预览" width="400px">
      <div class="preview-content">
        <div v-for="comp in components" :key="comp.id" class="preview-comp">
          {{ comp.name }}
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, h } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  ArrowLeft, MagicStick, Select, Promotion, RefreshLeft, RefreshRight,
  Delete, Top, Bottom, DocumentCopy, Picture, Grid, Document,
  ShoppingCart, PriceTag, Connection, Iphone, House, Menu, User
} from '@element-plus/icons-vue'

const activeNames = ref(['basic'])
const propertyTab = ref('component')
const currentPage = ref('首页')
const selectedIndex = ref(null)
const showAIDialog = ref(false)
const showPreview = ref(false)
const aiInput = ref('')
const aiGenerating = ref(false)

const pageData = reactive({
  title: '商城首页',
  bgColor: '#f5f5f5',
  shareImage: ''
})

const components = ref([])
const history = ref([])
const historyIndex = ref(-1)

const canUndo = computed(() => historyIndex.value > 0)
const canRedo = computed(() => historyIndex.value < history.value.length - 1)

const selectedComponent = computed(() => {
  return components.value[selectedIndex.value]
})

const pages = [
  { key: 'home', name: '首页' },
  { key: 'category', name: '分类' },
  { key: 'cart', name: '购物车' },
  { key: 'user', name: '个人中心' }
]

// 基础组件
const basicComponents = [
  { 
    type: 'banner', 
    name: '轮播图', 
    desc: '图片轮播',
    color: '#409eff',
    data: { 
      height: 200, 
      autoplay: true, 
      indicator: true,
      items: [
        { image: 'https://via.placeholder.com/375x200/409eff/ffffff?text=Banner+1' },
        { image: 'https://via.placeholder.com/375x200/67c23a/ffffff?text=Banner+2' }
      ]
    }
  },
  { 
    type: 'notice', 
    name: '公告栏', 
    desc: '滚动公告',
    color: '#e6a23c',
    data: { text: '欢迎来到我们的商城！', speed: 50 }
  },
  { 
    type: 'grid-nav', 
    name: '魔方导航', 
    desc: '图标导航',
    color: '#67c23a',
    data: { rows: 2, cols: 4 }
  },
  { 
    type: 'search', 
    name: '搜索栏', 
    desc: '商品搜索',
    color: '#909399',
    data: { placeholder: '搜索商品' }
  }
]

// 商品组件
const productComponents = [
  { 
    type: 'product-list', 
    name: '商品列表', 
    desc: '商品展示',
    color: '#409eff',
    data: { columns: 2, showTitle: true, showPrice: true }
  },
  { 
    type: 'product-scroll', 
    name: '横向滚动', 
    desc: '横向商品',
    color: '#67c23a',
    data: { count: 5 }
  },
  { 
    type: 'product-card', 
    name: '商品卡片', 
    desc: '单个商品',
    color: '#e6a23c',
    data: { productId: '' }
  }
]

// 营销组件
const marketingComponents = [
  { 
    type: 'coupon', 
    name: '优惠券', 
    desc: '领取优惠券',
    color: '#f56c6c',
    data: { title: '限时优惠' }
  },
  { 
    type: 'seckill', 
    name: '秒杀活动', 
    desc: '限时秒杀',
    color: '#e6a23c',
    data: { title: '限时秒杀' }
  },
  { 
    type: 'activity', 
    name: '活动专区', 
    desc: '营销活动',
    color: '#409eff',
    data: { title: '活动专区' }
  }
]

let dragComp = null

const handleDragStart = (comp) => {
  dragComp = comp
}

const handleDrop = () => {
  if (dragComp) {
    const newComp = {
      id: `comp_${Date.now()}`,
      type: dragComp.type,
      name: dragComp.name,
      data: JSON.parse(JSON.stringify(dragComp.data))
    }
    
    components.value.push(newComp)
    saveHistory()
  }
}

const renderComponent = (comp) => {
  return {
    name: `Mall${comp.type}`,
    props: ['data'],
    setup(props) {
      return () => {
        if (comp.type === 'banner') {
          return h('div', { class: 'comp-banner' }, [
            h('div', { class: 'banner-placeholder', style: `height: ${comp.data.height}px` }, [
              h('el-icon', { size: 48, color: '#409eff' }, { default: () => h(Picture) }),
              h('div', '轮播图 (' + comp.data.items.length + '张)')
            ])
          ])
        } else if (comp.type === 'notice') {
          return h('div', { class: 'comp-notice' }, [
            h('el-icon', { size: 16 }, { default: () => h(Document) }),
            h('span', comp.data.text)
          ])
        } else if (comp.type === 'grid-nav') {
          return h('div', { class: 'comp-grid' }, 
            `${comp.data.rows}行 × ${comp.data.cols}列导航`
          )
        } else if (comp.type === 'product-list') {
          return h('div', { class: 'comp-product-list' }, [
            h('div', { class: 'product-header' }, '商品列表'),
            h('div', { class: 'product-grid', style: `grid-template-columns: repeat(${comp.data.columns}, 1fr)` }, 
              Array(4).fill(0).map((_, i) => 
                h('div', { class: 'product-item' }, [
                  h('div', { class: 'product-image' }, '图片'),
                  comp.data.showTitle ? h('div', { class: 'product-title' }, '商品名称') : null,
                  comp.data.showPrice ? h('div', { class: 'product-price' }, '¥99.00') : null
                ])
              )
            )
          ])
        } else if (comp.type === 'seckill') {
          return h('div', { class: 'comp-seckill' }, [
            h('div', { class: 'seckill-title' }, comp.data.title),
            h('div', { class: 'seckill-time' }, '距结束：02:30:45')
          ])
        } else {
          return h('div', { class: 'comp-default' }, comp.name + ' 组件')
        }
      }
    }
  }
}

const selectComponent = (index) => {
  selectedIndex.value = index
}

const moveUp = (index) => {
  if (index > 0) {
    const temp = components.value[index]
    components.value[index] = components.value[index - 1]
    components.value[index - 1] = temp
    saveHistory()
  }
}

const moveDown = (index) => {
  if (index < components.value.length - 1) {
    const temp = components.value[index]
    components.value[index] = components.value[index + 1]
    components.value[index + 1] = temp
    saveHistory()
  }
}

const copyComponent = (index) => {
  const comp = JSON.parse(JSON.stringify(components.value[index]))
  comp.id = `comp_${Date.now()}`
  components.value.splice(index + 1, 0, comp)
  saveHistory()
}

const deleteComponent = (index) => {
  components.value.splice(index, 1)
  selectedIndex.value = null
  saveHistory()
}

const handleClear = () => {
  ElMessageBox.confirm('确定清空所有组件？', '提示', {
    type: 'warning'
  }).then(() => {
    components.value = []
    selectedIndex.value = null
    saveHistory()
    ElMessage.success('已清空')
  })
}

const saveHistory = () => {
  history.value = history.value.slice(0, historyIndex.value + 1)
  history.value.push(JSON.parse(JSON.stringify(components.value)))
  historyIndex.value = history.value.length - 1
}

const handleUndo = () => {
  if (canUndo.value) {
    historyIndex.value--
    components.value = JSON.parse(JSON.stringify(history.value[historyIndex.value]))
  }
}

const handleRedo = () => {
  if (canRedo.value) {
    historyIndex.value++
    components.value = JSON.parse(JSON.stringify(history.value[historyIndex.value]))
  }
}

const addBannerItem = () => {
  if (selectedComponent.value) {
    selectedComponent.value.data.items.push({
      image: 'https://via.placeholder.com/375x200'
    })
  }
}

const removeBannerItem = (index) => {
  if (selectedComponent.value) {
    selectedComponent.value.data.items.splice(index, 1)
  }
}

const switchPage = (pageKey) => {
  const page = pages.find(p => p.key === pageKey)
  if (page) {
    currentPage.value = page.name
  }
}

const handleSave = () => {
  console.log('保存页面:', { pageData, components: components.value })
  ElMessage.success('保存成功')
}

const handlePublish = () => {
  ElMessageBox.confirm('确定发布此页面？', '提示', {
    type: 'info'
  }).then(() => {
    handleSave()
    ElMessage.success('发布成功')
  })
}

const handleAIGenerate = () => {
  if (!aiInput.value.trim()) {
    ElMessage.warning('请输入需求描述')
    return
  }

  aiGenerating.value = true

  setTimeout(() => {
    components.value = [
      {
        id: 'comp_1',
        type: 'banner',
        name: '轮播图',
        data: {
          height: 200,
          autoplay: true,
          indicator: true,
          items: [
            { image: 'https://via.placeholder.com/375x200/409eff/ffffff?text=促销+1' },
            { image: 'https://via.placeholder.com/375x200/67c23a/ffffff?text=促销+2' }
          ]
        }
      },
      {
        id: 'comp_2',
        type: 'grid-nav',
        name: '魔方导航',
        data: { rows: 2, cols: 4 }
      },
      {
        id: 'comp_3',
        type: 'seckill',
        name: '秒杀活动',
        data: { title: '限时秒杀' }
      },
      {
        id: 'comp_4',
        type: 'product-list',
        name: '商品列表',
        data: { columns: 2, showTitle: true, showPrice: true }
      }
    ]

    ElMessage.success('页面生成成功')
    aiGenerating.value = false
    showAIDialog.value = false
    saveHistory()
  }, 2000)
}

saveHistory()
</script>

<style scoped>
.mall-diy-designer {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f0f2f5;
}

.designer-header {
  height: 60px;
  background: white;
  border-bottom: 1px solid #e6e6e6;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.back-icon {
  font-size: 20px;
  cursor: pointer;
}

.title {
  font-size: 18px;
  font-weight: bold;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.designer-body {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.component-panel {
  width: 280px;
  background: white;
  border-right: 1px solid #e6e6e6;
  overflow-y: auto;
}

.panel-header {
  padding: 15px;
  font-weight: bold;
  border-bottom: 1px solid #e6e6e6;
}

.component-list {
  padding: 10px;
}

.component-item {
  display: flex;
  gap: 12px;
  padding: 12px;
  margin-bottom: 10px;
  background: #f9f9f9;
  border: 1px solid #e6e6e6;
  border-radius: 6px;
  cursor: move;
  transition: all 0.3s;
}

.component-item:hover {
  background: #e6f7ff;
  border-color: #409eff;
  transform: translateX(5px);
}

.comp-info {
  flex: 1;
}

.comp-name {
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 4px;
}

.comp-desc {
  font-size: 12px;
  color: #909399;
}

.preview-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
}

.preview-toolbar {
  display: flex;
  justify-content: space-between;
  width: 100%;
  max-width: 400px;
  margin-bottom: 20px;
  gap: 10px;
}

.mobile-preview {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: flex-start;
}

.mobile-device {
  width: 375px;
  height: 667px;
  background: white;
  border-radius: 30px;
  box-shadow: 0 10px 50px rgba(0,0,0,0.2);
  overflow: hidden;
  display: flex;
  flex-direction: column;
  border: 8px solid #2c3e50;
}

.device-header {
  height: 44px;
  background: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 15px;
  border-bottom: 1px solid #f0f0f0;
  font-size: 12px;
}

.status-bar {
  display: flex;
  gap: 8px;
}

.device-content {
  flex: 1;
  overflow-y: auto;
  background: #f5f5f5;
}

.device-footer {
  height: 60px;
  background: white;
  border-top: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-around;
}

.nav-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 4px;
  font-size: 12px;
  color: #999;
  cursor: pointer;
  transition: all 0.3s;
}

.nav-item.active {
  color: #409eff;
}

.page-component {
  position: relative;
  margin-bottom: 10px;
  background: white;
  border: 2px solid transparent;
  transition: all 0.3s;
}

.page-component:hover {
  border-color: #409eff;
}

.page-component.active {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.component-toolbar {
  position: absolute;
  top: 5px;
  right: 5px;
  opacity: 0;
  transition: opacity 0.3s;
}

.page-component:hover .component-toolbar,
.page-component.active .component-toolbar {
  opacity: 1;
}

.property-panel {
  width: 300px;
  background: white;
  border-left: 1px solid #e6e6e6;
  overflow-y: auto;
}

.property-form {
  padding: 15px;
}

.property-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e6e6e6;
}

.banner-item {
  display: flex;
  gap: 5px;
  margin-top: 5px;
}

/* 组件样式 */
.comp-banner {
  width: 100%;
}

.banner-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  gap: 10px;
}

.comp-notice {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px 15px;
  background: #fffbe6;
  color: #e6a23c;
  font-size: 13px;
}

.comp-grid {
  padding: 15px;
  background: white;
  text-align: center;
  color: #67c23a;
  font-weight: bold;
}

.comp-product-list {
  padding: 15px;
  background: white;
}

.product-header {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
}

.product-grid {
  display: grid;
  gap: 10px;
}

.product-item {
  border: 1px solid #e6e6e6;
  border-radius: 8px;
  overflow: hidden;
}

.product-image {
  height: 150px;
  background: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
}

.product-title {
  padding: 8px;
  font-size: 13px;
}

.product-price {
  padding: 0 8px 8px;
  color: #f56c6c;
  font-weight: bold;
}

.comp-seckill {
  padding: 15px;
  background: linear-gradient(135deg, #f56c6c 0%, #e6a23c 100%);
  color: white;
}

.seckill-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 5px;
}

.seckill-time {
  font-size: 14px;
}

.comp-default {
  padding: 30px;
  text-align: center;
  color: #999;
  background: white;
}
</style>

